"""
@author: 周末
--------------------------------------
@project: application
--------------------------------------
@contact:15892766524@163.com
--------------------------------------
@file: Db.py
--------------------------------------
@time: 2021/11/12 11:54
--------------------------------------
"""
import pymysql
from pymysql.cursors import DictCursor


class Db(object):
    def __init__(self, host: str = '127.0.0.1', user: str = 'root', password: str = 'root', port: int = 3306,
                 db: str = '',
                 charset: str = 'utf8'):
        """
        数据库链接信息
        :param host: 链接地址
        :param user: 用户名
        :param password: 密码
        :param port: 端口
        :param db: 数据库
        :param charset: 字符集
        """
        self.__cnn = pymysql.connect(host=host, user=user, password=password, db=db, port=port, charset=charset)

    def __del__(self):
        """
        关闭数据库链接
        :return: None
        """
        self.__cnn.close()

    def fetchOne(self, sql, args=None):
        """
        查询单条数据
        :param sql: 查询语句
        :param args: 查询条件 主要防止sql注入
        :return:
        """
        with self.__cnn.cursor(cursor=DictCursor) as cursor:
            cursor.execute(sql, args)
            return cursor.fetchone()

    def fetchall(self, sql, args=None):
        """
        查询多条数据
        :param sql: 查询语句
        :param args: 查询条件 主要防止sql注入
        :return:
        """
        with self.__cnn.cursor(cursor=DictCursor) as cursor:
            cursor.execute(sql, args)
            return cursor.fetchall()


if __name__ == '__main__':
    db = Db(host='139.159.146.104', user='root', password='itsource.cn..', port=3306, db='03_mall',
            charset='utf8')
    # sql = "select * from ums_member where username = %s"
    sql = 'select username from ums_member where username like "%Tomcat%"'
    # print(db.fetchOne(sql, ('Tomcat_16890000584',)))
    print(db.fetchall(sql))
